/**
 * 5234. 移除字母异位词后的结果数组
 * https://leetcode.cn/contest/weekly-contest-293/problems/find-resultant-array-after-removing-anagrams/
 */
const { displayBaseArray } = require('../../libs/public');

const codeA = 'a'.charCodeAt(0);

/**
 * @param {string[]} words
 * @return {string[]}
 */
function removeAnagrams(words) {
  if (words.length <= 1) {
    return words;
  }
  const counts = new Array(26);
  let begin = 0;
  const result = [];
  while (begin < words.length) {
    const cur = words[begin];
    result.push(cur);
    let next = begin + 1;
    if (next === words.length || words[next].length !== cur.length) {
      begin = next;
      continue;
    }
    counts.fill(0);
    for (let i = 0; i < cur.length; i += 1) {
      counts[cur.charCodeAt(i) - codeA] += 1;
    }
    for (; next < words.length; next += 1) {
      const str = words[next];
      if (str.length !== cur.length) {
        break;
      }
      let rest = cur.length;
      const cache = Array.from(counts);
      for (let i = 0; i < str.length; i += 1) {
        const index = str.charCodeAt(i) - codeA;
        if (cache[index]) {
          cache[index] -= 1;
          rest -= 1;
        } else {
          break;
        }
      }
      if (rest !== 0) {
        break;
      }
    }
    begin = next;
  }
  return result;
}

console.log(displayBaseArray(removeAnagrams(['abba', 'baba', 'bbaa', 'cd', 'cd'])) === '[abba,cd]');
console.log(displayBaseArray(removeAnagrams(['a', 'b', 'c', 'd', 'e'])) === '[a,b,c,d,e]');
console.log(displayBaseArray(removeAnagrams(['klxkw', 'kkwlx', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'm', 'mkzbqw', 'qwzbmk', 'kbmqwz', 'bkzwmq', 'qmzkwb'])) === '[klxkw,m,mkzbqw]');
